﻿using DiLe.Mes.Application.Cloud.Statistics;
using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Model.Cloud.Dashboard.Statistics;
using DiLe.Mes.Model.Cloud.Statistics;
using DiLe.Mes.Model.Common.APP;
using DiLe.Mes.Model.Common.Equipment.Entity.Manage;
using DiLe.Mes.Model.Common.Mould.Entity.Info;
using DiLe.Mes.Model.Common.Organization.Entity;
using DiLe.Mes.Model.Common.Process.Entity;
using MapleLeaf.Core.Cryptogram;
using MapleLeaf.Core.Filter;
using Microsoft.AspNetCore.Authorization;
using MiniExcelLibs;
using MiniExcelLibs.OpenXml;
using Newtonsoft.Json.Linq;

namespace DiLe.Mes.Cloud.Controllers {
    /// <summary>
    /// 
    /// </summary>
    [ApiExplorerSettings(GroupName = ApiCloudGroupConst.Dashboard)]
    public class InitController : ApiBaseController {


        private readonly EquipmentManageClient _equipmentManage;
        private readonly StatisticsClient _statisticsClient;
        private readonly IWebHostEnvironment _webHostEnvironment;
        /// <summary>
        /// 
        /// </summary>
        public InitController(IWebHostEnvironment webHostEnvironment, EquipmentManageClient equipmentManageClient, StatisticsClient statisticsClient) {
            _equipmentManage = equipmentManageClient;
            _statisticsClient = statisticsClient;
            _webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 同步-返回数据
        /// </summary>
        [HttpGet, HiddenApi, AllowAnonymous]
        public async Task<ApiResult> SynchronousReturn(string key) {
            var info = new SynchronousInfo();
            var appkey = AppHelper.GetConfig("AppSetting", "Appkey");
            string data = MD5Helper.CalculateMD5(appkey);
            if (key != data) {
                return Fail("客户端未授权！");
            }
            //用户
            info.UserInfos = await SqlSugarHelper.MasterDb.Queryable<UserEntity>().ToListAsync();
            //角色
            info.RoleInfos = await SqlSugarHelper.MasterDb.Queryable<RoleEntity>().ToListAsync();


            //设备档案
            info.EquipmentInfoList = await SqlSugarHelper.MasterDb.Queryable<EquipmentInfoEntity>().ToListAsync();
            //设备类型
            info.EquipmentTypeList = await SqlSugarHelper.MasterDb.Queryable<EquipmentTypeEntity>().ToListAsync();
            //设备状态
            info.EquipmentStatusList = await SqlSugarHelper.MasterDb.Queryable<EquipmentStatusEntity>().ToListAsync();


            //模具档案
            info.MouldInfoList = await SqlSugarHelper.MasterDb.Queryable<MouldInfoEntity>().ToListAsync();
            //模具类型
            info.MouldTypeList = await SqlSugarHelper.MasterDb.Queryable<MouldTypeEntity>().ToListAsync();
            //模具状态
            info.MouldStatusList = await SqlSugarHelper.MasterDb.Queryable<MouldStatusEntity>().ToListAsync();

            //制程
            info.ProcessList = await SqlSugarHelper.MasterDb.Queryable<ProcessEntity>().ToListAsync();

            //设备注册
            info.EquipmentRegisterList = await SqlSugarHelper.MasterDb.Queryable<EquipmentRegisterEntity>().ToListAsync();



            return Success(info);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public ApiResult UploadAlarmInfo(IFormFile file) {
            var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempfile");
            if (!Directory.Exists(dir)) {
                Directory.CreateDirectory(dir);
            }
            var filefullPath = Path.Combine(dir, file.FileName);
            using (FileStream fs = new(filefullPath, FileMode.Create)) {
                file.CopyTo(fs);
                fs.Flush();
            }
            var config = new OpenXmlConfiguration() {
                FillMergedCells = true
            };
            var rows = MiniExcel.Query(filefullPath, configuration: config).Cast<IDictionary<string, object>>();
            var headerRow = rows.FirstOrDefault();
            var maps = new List<(string key, string name)>();
            foreach (var key in headerRow!.Keys) {
                maps.Add((key, headerRow[key]?.ToString() ?? ""));
            }
            //var rowDatas = rows.Skip(1).ToList();

            //var typeList = await SqlSugarHelper.MasterDb.Queryable<EquipmentTypeEntity>().ToListAsync();


            //var list = new List<AbnormalAlarmInfoEntity>();
            //foreach (var rowData in rowDatas) {
            //    var m = new AbnormalAlarmInfoEntity();
            //    foreach (var (key, name) in maps) {
            //        var value = rowData[key];
            //        switch (name) {
            //            case "报警信息":
            //                m.AlarmName = value?.ToString() ?? "";
            //                break;
            //            case "描述":
            //                m.AlarmDescription = value?.ToString() ?? "";
            //                break;
            //            case "报警级别":
            //                m.AlarmLevel = value?.ToInt() ?? 0;
            //                break;
            //            case "备注":
            //                var t = typeList?.FirstOrDefault(x => x.Code == value?.ToString());
            //                m.EquipmentTypeId = t?.Id ?? 0;
            //                break;
            //            default:
            //                break;
            //        }
            //    }
            //    if (m.EquipmentTypeId == 0) {
            //        continue;
            //    }
            //    list.Add(m);
            //}
            //await SqlSugarHelper.MasterDb.Deleteable<AbnormalAlarmInfoEntity>().ExecuteCommandAsync();
            //await SqlSugarHelper.MasterDb.Insertable(list).ExecuteCommandAsync();
            return Success();

        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public ApiResult GetResult() {
            //var f1 = Path.Combine(_hostingEnvironment.WebRootPath, "zh-cn.json");
            //var f1jsonString = System.IO.File.ReadAllText(f1);
            //// 反序列化JSON字符串为动态类型
            //JObject jsonObject = JObject.Parse(f1jsonString);
            //// 转换为Dictionary<string, string>
            //Dictionary<string, string> f1dic = FlattenJsonObject(jsonObject);

            //var f2 = Path.Combine(_hostingEnvironment.WebRootPath, "en.json");
            //var f2jsonString = System.IO.File.ReadAllText(f2);
            //// 反序列化JSON字符串为动态类型
            //JObject f2jsonObject = JObject.Parse(f2jsonString);
            //Dictionary<string, string> f2dic = FlattenJsonObject(f2jsonObject);

            //var f3 = Path.Combine(_hostingEnvironment.WebRootPath, "cht.json");
            //var f3jsonString = System.IO.File.ReadAllText(f3);
            //// 反序列化JSON字符串为动态类型
            //JObject f3jsonObject = JObject.Parse(f3jsonString);
            //Dictionary<string, string> f3dic = FlattenJsonObject(f3jsonObject);


            var list = new List<(string key, string zh, string en, string cht)>();

            //foreach (var key in f1dic.Keys) {
            //    var val = f1dic[key];
            //    string va12 = "";
            //    if (f2dic.ContainsKey(key)) {
            //        va12 = f2dic[key];
            //    }
            //    string va13 = "";
            //    if (f3dic.ContainsKey(key)) {
            //        va13 = f3dic[key];
            //    }
            //    list.Add((key, val, va12, va13));
            //}
            return Success(list);
        }
        // 将嵌套的动态类型对象展平为Dictionary<string, string>
        private static Dictionary<string, string> FlattenJsonObject(JObject jsonObj) {
            Dictionary<string, string> result = [];

            foreach (var property in jsonObj.Properties()) {
                JToken value = property.Value;

                // 如果值是字符串类型，则将键值对添加到结果字典中
                if (value.Type == JTokenType.String) {
                    result.Add(property.Name, value.ToString());
                }
                // 如果值是动态类型对象，则递归调用该方法，将其展平后的键值对添加到结果字典中
                else {
                    var nestedDict = FlattenJsonObject((JObject)value);
                    foreach (var pair in nestedDict) {
                        result.Add(property.Name + "." + pair.Key, pair.Value);
                    }
                }
            }
            return result;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public ApiResult Test() {

            // 获取 UTC+08:00 的时区信息
            TimeZoneInfo utc8TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai");

            // 将当前时间转换为中国标准时间
            DateTime utc8Time = DateTime.Parse("2023-12-08 23:54:47.426");
            DateTime chinaTime = TimeZoneInfo.ConvertTime(utc8Time, utc8TimeZone, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));

            Console.WriteLine("当前 UTC+08:00 时间： " + utc8Time);
            Console.WriteLine("中国标准时间： " + chinaTime);
            return Success();
        }
        /// <summary>
        /// 同步请求
        /// </summary>
        [HttpPost, AllowAnonymous]
        public ApiResult SynchronousEquipmentStatistics(List<EquipmentStatisticsEntity> models) {
            if (models == null && models.None()) {
                return Fail();
            }
            var date = models.First().Date;
            _statisticsClient.DeletEquipmentStatisticsList(p => p.Date == date);
            //插入
            var res = _statisticsClient.InsertEquipmentStatistics(models) > 0;
            return res ? Success() : Fail();
        }

        /// <summary>
        /// 同步请求
        /// </summary>
        [HttpPost, AllowAnonymous]
        public ApiResult SynchronousEquipmentOutputStatistics(List<EquipmentOutputStatisticsEntity> models) {
            if (models == null && models.None()) {
                return Fail();
            }
            //插入
            var res = _statisticsClient.InsertEquipmentOutputStatistics(models) > 0;
            return res ? Success() : Fail();
        }


       
    }
    /// <summary>
    /// 
    /// </summary>
    public class SynchronousInfo {
        /// <summary>
        /// 
        /// </summary>
        public List<UserEntity> UserInfos { set; get; }
        /// <summary>
        /// 
        /// </summary>
        public List<RoleEntity> RoleInfos { set; get; }

        /// <summary>
        /// 设备档案
        /// </summary>
        public List<EquipmentInfoEntity> EquipmentInfoList { set; get; }
        /// <summary>
        /// 设备类型
        /// </summary>
        public List<EquipmentTypeEntity> EquipmentTypeList { set; get; }
        /// <summary>
        /// 设备状态
        /// </summary>
        public List<EquipmentStatusEntity> EquipmentStatusList { set; get; }

        /// <summary>
        /// 模具档案
        /// </summary>
        public List<MouldInfoEntity> MouldInfoList { set; get; }
        /// <summary>
        /// 模具类型
        /// </summary>
        public List<MouldTypeEntity> MouldTypeList { set; get; }
        /// <summary>
        /// 模具状态
        /// </summary>
        public List<MouldStatusEntity> MouldStatusList { set; get; }
        /// <summary>
        /// 制程
        /// </summary>
        public List<ProcessEntity> ProcessList { set; get; }

        /// <summary>
        /// 注册信息
        /// </summary>
        public List<EquipmentRegisterEntity> EquipmentRegisterList { set; get; }


    }

}
